package lion.dev.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lion.dev.matcher.IncluceMatcher;
import lion.dev.matcher.Matcher;
import lion.dev.matcher.WildCardMatch;

public class FileFinder {

	private List<Matcher> matchers = new ArrayList<>();// 通配
	private boolean searchHidden = false;

	public FileFinder(boolean searchHidden, String... patterns) {

		this.searchHidden = searchHidden;

		for (String p : patterns) {
			if (p.indexOf("*") > -1) {
				matchers.add(new WildCardMatch(p));
			} else {
				matchers.add(new IncluceMatcher(p));
			}
		}

		if (matchers.isEmpty()) {
			matchers.add(new WildCardMatch("*"));
		}
	}

	public FileFinder(String... patterns) {

		this(false, patterns);
	}

	public List<File> find(File f) {

		List<File> result = new ArrayList<>();
		search(f, result);
		return result;
	}

	public List<File> find(String f) {

		return find(new File(f));
	}

	public void setSearchHidden(boolean searchHidden) {

		this.searchHidden = searchHidden;
	}

	private void search(File parent, List<File> result) {

		if (parent.isFile()) {
			for (Matcher m : this.matchers) {
				if (m.match(parent.getName())) {
					result.add(parent);
					break;
				}
			}
		} else {
			for (File sub : parent.listFiles()) {
				if (sub.isHidden() && !searchHidden) {
					continue;
				}
				search(sub, result);
			}
		}
	}
}
